// 基于Web API的窗口管理工具
import { DialogItem } from '@/types/dialog'

export class WindowManager {
  private static openWindows: Map<string, Window> = new Map()

  // 创建独立的弹出窗口
  static async createPopupWindow(config: {
    url: string
    width?: number
    height?: number
    x?: number
    y?: number
    title?: string
    features?: string
  }): Promise<Window | null> {
    const {
      url,
      width = 400,
      height = 600,
      x = 100,
      y = 100,
      title = 'AI对话',
      features = ''
    } = config

    // 构建窗口特性字符串
    const windowFeatures = [
      `width=${width}`,
      `height=${height}`,
      `left=${x}`,
      `top=${y}`,
      'resizable=yes',
      'scrollbars=no',
      'toolbar=no',
      'menubar=no',
      'location=no',
      'status=no',
      features
    ].filter(Boolean).join(',')

    try {
      // 创建弹出窗口
      const popup = window.open(url, title, windowFeatures)
      
      if (!popup) {
        throw new Error('弹出窗口被浏览器阻止')
      }

      // 设置窗口标题
      popup.document.title = title

      // 存储窗口引用
      this.openWindows.set(title, popup)

      // 监听窗口关闭事件
      const checkClosed = setInterval(() => {
        if (popup.closed) {
          this.openWindows.delete(title)
          clearInterval(checkClosed)
        }
      }, 1000)

      return popup
    } catch (error) {
      console.error('创建弹出窗口失败:', error)
      throw error
    }
  }

  // 创建聊天对话框窗口
  static async createChatWindow(config: DialogItem) {
    const { width, height } = config.dialog_size
    const features = `width=${width},height=${height},left=${(window.screen.width - width) / 2},top=${(window.screen.height - height) / 2}`
    const url = `${window.location.origin}/chat?scene_id=${config.scene_id}`
    return window.open(url, 'chat_window', features)
  }

  static async createVoiceCallWindow(config: DialogItem) {
    const { width, height } = config.dialog_size
    const features = `width=${width},height=${height},left=${(window.screen.width - width) / 2},top=${(window.screen.height - height) / 2}`
    const url = `${window.location.origin}/voice-call?scene_id=${config.scene_id}`
    return window.open(url, 'voice_call_window', features)
  }

  static async createVideoCallWindow(config: DialogItem) {
    const { width, height } = config.dialog_size
    const features = `width=${width},height=${height},left=${(window.screen.width - width) / 2},top=${(window.screen.height - height) / 2}`
    const url = `${window.location.origin}/video-call?scene_id=${config.scene_id}`
    return window.open(url, 'video_call_window', features)
  }

  // 关闭指定窗口
  static closeWindow(title: string): void {
    const popup = this.openWindows.get(title)
    if (popup && !popup.closed) {
      popup.close()
      this.openWindows.delete(title)
    }
  }

  // 关闭所有窗口
  static closeAllWindows(): void {
    this.openWindows.forEach((popup, title) => {
      if (!popup.closed) {
        popup.close()
      }
    })
    this.openWindows.clear()
  }

  // 获取窗口引用
  static getWindow(title: string): Window | null {
    const popup = this.openWindows.get(title)
    return popup && !popup.closed ? popup : null
  }

  // 聚焦到指定窗口
  static focusWindow(title: string): boolean {
    const popup = this.getWindow(title)
    if (popup) {
      popup.focus()
      return true
    }
    return false
  }

  // 检查窗口是否存在
  static hasWindow(title: string): boolean {
    return !!this.getWindow(title)
  }

  // 向窗口发送消息
  static postMessage(title: string, message: any): boolean {
    const popup = this.getWindow(title)
    if (popup) {
      popup.postMessage(message, window.location.origin)
      return true
    }
    return false
  }

  // 监听来自弹出窗口的消息
  static onMessage(callback: (event: MessageEvent) => void): void {
    window.addEventListener('message', callback)
  }

  // 移除消息监听器
  static offMessage(callback: (event: MessageEvent) => void): void {
    window.removeEventListener('message', callback)
  }
}

// 页面卸载时关闭所有弹出窗口
window.addEventListener('beforeunload', () => {
  WindowManager.closeAllWindows()
}) 